<?php
namespace Duobao\Model;

use Think\Model;
use Org\Util\JWT as JWT;
use Duobao\Controller\LogController as Mylog;

class UserModel extends Model{

    protected $tableName = 'member';

    /**
     * 用户登陆
     */
    public function Login($username,$password){
        $result['status'] ='';
        $result['token'] = '';

        $where = array();
        $where['mobile'] = $username;

        $dbret = $this->field('uid,password')->where($where)->find();

        if($dbret['password'] == md5($password)){
            $result['status'] = 'ok';
            $result['token'] = JWT::encode($dbret['uid'].':'.time(),C("SECRET_KEY"),"HS256");
        }else{
            $result['status'] = 'error';
        }

        return $result;
    }

    /**
     * 微信登陆
     */
    public function wxLogin(){
        echo '这里是微信login ';
    }

    /**
     * 这里是注册
     */
    public function Register($phone,$password,$msgcode){
        #检测当前的用户最后一次输入的手机号码与验证码是否对应
        $model = new \Think\Model();
        $where['phone'] = $phone;
        $where['time'] = array('gt',time()-300);
        $result = $model->table('__MESSAGE__')->where($where)->field('time,code')->order('time desc')->find();
        #分割发送的内容
        if(!($result['code'] == $msgcode)){
            return false;
        }else{
            $data['mobile'] = $phone;
            $data['password'] = md5($password);
            $data['mobilecode'] = 0;
            $condition['mobile'] = $phone;

            if($this->query("select * from __PREFIX__member WHERE mobile=$phone")){
                return false;#number is exist
            }else{

                #手机号注册时候也加2个夺宝币
                #新用户关注送n个夺宝币,获取配置表中，用户关注送币的开关
                $config = $model->query("select `value` from __PREFIX__config where name IN('follow_switch','follow_money','follow_each') ORDER BY id");

//        foreach($config as $value){
//            MyLog::write($value);
//        }
                $follow_switch = $config[0]['value'];
                $follow_money =  $config[1]['value'];
                $follow_each = $config[2]['value'];
                // MyLog::write($follow_each.":".$follow_money.":".$follow_switch);
                if($follow_switch != 0 && $follow_money > 0){

                    #将config表中的钱减2
                    $update = $model->execute("update __PREFIX__config set `value`=`value` - $follow_each WHERE name = 'follow_money'");
                    if(!$update){
                        MyLog::write('新用户加钱失败');
                    }else{
                        $data['money'] = $follow_each;
                    }
                }
                return $this->data($data)->add();
            }
        }
    }

    /* end of user model */
}
